/// Copyright 2007-8 Faraday Media
/// 
/// Licensed under the Apache License, Version 2.0 (the "License"); 
/// you may not use this file except in compliance with the License. 
/// You may obtain a copy of the License at 
/// 
///   http://www.apache.org/licenses/LICENSE-2.0 
/// 
/// Unless required by applicable law or agreed to in writing, software 
/// distributed under the License is distributed on an "AS IS" BASIS, 
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
/// See the License for the specific language governing permissions and 
/// limitations under the License.
using System;
using System.CodeDom;
using System.Reflection;
using System.Xml.Serialization;

namespace MetaSharp.XML.Strategies {
  /// <summary>
  /// Strategy used to handle retrieving attibute values.
  /// </summary>
  public class AttributeStrategy : BaseStrategy, IPropertyStrategy {
    #region IStrategy Members
    /// <summary>
    /// Defines that this strategy is base code.
    /// </summary>
    public override StrategyPriority Priority {
      get { return StrategyPriority.BaseCode; }
    }
    #endregion

    #region IPropertyStrategy Members
    /// <summary>
    /// Checks whether the given strategy applies to a property.
    /// </summary>
    /// <param name="pProp">the property to check</param>
    /// <returns>true - strategies apply</returns>
    public bool AppliesToProperty(PropertyInfo pProp) {
      XmlAttributeAttribute attrTag = AttributeHelper.GetAttribute<XmlAttributeAttribute>(pProp);
      return (attrTag != null);
    }

    /// <summary>
    /// Applies the strategy to the given property by generating code that will retrieve an attribute value.
    /// </summary>
    /// <param name="pContext">the context of the generation</param>
    /// <param name="pProp">the declared property</param>
    /// <param name="pGeneratedProp">the property being generated</param>
    /// <param name="pClass">the class being declared</param>
    public void Apply(GenerationContext pContext, PropertyInfo pProp, CodeMemberProperty pGeneratedProp, CodeTypeDeclaration pClass) {
      pClass.Members.Add(MethodHelper.GenerateCacheField(pProp));

      if (pProp.CanRead) {
        pGeneratedProp.GetStatements.AddRange(MethodHelper.GenerateSimpleGetMethod(
          pProp, delegate(Type pType, object pDefaultValue) {
                   CodeMethodInvokeExpression getInvoke = new CodeMethodInvokeExpression(
                     new CodeThisReferenceExpression(), "GetAttributeOrDefault",
                     new CodePrimitiveExpression(SelectAttributeName(pProp)),
                     new CodePrimitiveExpression(pDefaultValue));

                   getInvoke.Method.TypeArguments.Add(new CodeTypeReference(pType));
                   return getInvoke;
                 }));
      }
      if (pProp.CanWrite) {
        pGeneratedProp.SetStatements.AddRange(MethodHelper.GenerateSimpleSetMethod(
          pProp, delegate(Type pType, CodeExpression pValueExpr) {
                   CodeMethodInvokeExpression setExpr =
                     new CodeMethodInvokeExpression(
                       new CodeThisReferenceExpression(), "SetAttribute",
                       new CodePrimitiveExpression(SelectAttributeName(pProp)),
                       pValueExpr
                       );
                   setExpr.Method.TypeArguments.Add(new CodeTypeReference(pType));
                   return setExpr;
                 }));
      }
    }

    #endregion

    private static string SelectAttributeName(MemberInfo pProp) {
      XmlAttributeAttribute attrTag = AttributeHelper.GetAttribute<XmlAttributeAttribute>(pProp);
      if (attrTag.AttributeName != null && attrTag.AttributeName != string.Empty) {
        return attrTag.AttributeName;
      }

      return pProp.Name;
    }
  }
}
